package com.adnaan.admin.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.adnaan.admin.model.entity.SysRole;
import com.adnaan.admin.service.SysRoleService;
import com.adnaan.common.model.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 系统角色管理控制器
 */
@Tag(name = "系统角色管理", description = "系统角色管理接口")
@RestController
@RequestMapping("/admin/system/role")
@RequiredArgsConstructor
public class SysRoleController {

    private final SysRoleService sysRoleService;

    /**
     * 分页查询角色列表
     */
    @Operation(summary = "分页查询角色列表", description = "分页查询系统角色列表")
    @SaCheckPermission("system:role:list")
    @GetMapping("/list")
    public Result<IPage<SysRole>> list(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "roleName", required = false) String roleName,
            @RequestParam(value = "roleKey", required = false) String roleKey,
            @RequestParam(value = "status", required = false) Integer status) {

        // 构建查询条件
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(roleName), SysRole::getRoleName, roleName)
                .like(StringUtils.hasText(roleKey), SysRole::getRoleKey, roleKey)
                .eq(status != null, SysRole::getStatus, status)
                .orderByAsc(SysRole::getRoleSort);

        // 执行分页查询
        IPage<SysRole> page = sysRoleService.page(new Page<>(pageNum, pageSize), queryWrapper);

        return Result.success(page);
    }

    /**
     * 获取角色详情
     */
    @Operation(summary = "获取角色详情", description = "根据角色ID获取角色详情")
    @SaCheckPermission("system:role:query")
    @GetMapping("/{id}")
    public Result<SysRole> getInfo(@PathVariable Long id) {
        SysRole role = sysRoleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        return Result.success(role);
    }

    /**
     * 添加角色
     */
    @Operation(summary = "添加角色", description = "添加系统角色")
    @SaCheckPermission("system:role:add")
    @PostMapping
    public Result<Void> add(@RequestBody SysRole role) {
        // 校验角色权限标识是否已存在
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getRoleKey, role.getRoleKey());
        if (sysRoleService.count(queryWrapper) > 0) {
            return Result.error("角色权限标识已存在");
        }

        // 保存角色
        sysRoleService.save(role);

        // 如果有菜单ID，分配菜单权限
        if (role.getMenuIds() != null && role.getMenuIds().length > 0) {
            sysRoleService.assignRoleMenus(role.getId(), role.getMenuIds());
        }

        return Result.success();
    }

    /**
     * 修改角色
     */
    @Operation(summary = "修改角色", description = "修改系统角色")
    @SaCheckPermission("system:role:edit")
    @PutMapping
    public Result<Void> update(@RequestBody SysRole role) {
        // 校验角色是否存在
        SysRole existRole = sysRoleService.getById(role.getId());
        if (existRole == null) {
            return Result.error("角色不存在");
        }

        // 校验角色权限标识是否重复
        if (!existRole.getRoleKey().equals(role.getRoleKey())) {
            LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysRole::getRoleKey, role.getRoleKey());
            if (sysRoleService.count(queryWrapper) > 0) {
                return Result.error("角色权限标识已存在");
            }
        }

        // 更新角色
        sysRoleService.updateById(role);

        // 如果有菜单ID，更新菜单权限
        if (role.getMenuIds() != null && role.getMenuIds().length > 0) {
            sysRoleService.assignRoleMenus(role.getId(), role.getMenuIds());
        }

        return Result.success();
    }

    /**
     * 删除角色
     */
    @Operation(summary = "删除角色", description = "删除系统角色")
    @SaCheckPermission("system:role:remove")
    @DeleteMapping("/{ids}")
    public Result<Void> remove(@PathVariable Long[] ids) {
        // 删除角色
        List<Long> idList = Arrays.asList(ids);
        sysRoleService.removeByIds(idList);

        // 删除角色菜单关联
        for (Long roleId : ids) {
            sysRoleService.assignRoleMenus(roleId, new Long[0]);
        }

        return Result.success();
    }

    /**
     * 修改角色状态
     */
    @Operation(summary = "修改角色状态", description = "启用/禁用角色")
    @SaCheckPermission("system:role:edit")
    @PutMapping("/changeStatus")
    public Result<Void> changeStatus(@RequestBody SysRole role) {
        // 校验角色是否存在
        SysRole existRole = sysRoleService.getById(role.getId());
        if (existRole == null) {
            return Result.error("角色不存在");
        }

        // 修改状态
        SysRole updateRole = new SysRole();
        updateRole.setId(role.getId());
        updateRole.setStatus(role.getStatus());

        sysRoleService.updateById(updateRole);

        return Result.success();
    }

    /**
     * 分配角色菜单权限
     */
    @Operation(summary = "分配角色菜单权限", description = "设置角色菜单权限")
    @SaCheckPermission("system:role:edit")
    @PutMapping("/assignMenu")
    public Result<Void> assignRoleMenu(@RequestBody SysRole role) {
        // 校验角色是否存在
        SysRole existRole = sysRoleService.getById(role.getId());
        if (existRole == null) {
            return Result.error("角色不存在");
        }

        // 分配菜单权限
        sysRoleService.assignRoleMenus(role.getId(), role.getMenuIds());

        return Result.success();
    }

    /**
     * 查询用户角色ID列表
     */
    @Operation(summary = "查询用户角色ID列表", description = "获取用户已分配的角色ID列表")
    @SaCheckPermission("system:role:query")
    @GetMapping("/userRoleIds/{userId}")
    public Result<List<Long>> getUserRoleIds(@PathVariable Long userId) {
        List<Long> roleIds = sysRoleService.getRoleIdsByUserId(userId);
        return Result.success(roleIds);
    }

    /**
     * 查询所有角色列表（不分页）
     */
    @Operation(summary = "查询所有角色列表", description = "获取所有可用角色列表，用于下拉选择")
    @SaCheckPermission("system:role:query")
    @GetMapping("/all")
    public Result<List<SysRole>> all() {
        // 只查询正常状态的角色
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getStatus, 0)
                .orderByAsc(SysRole::getRoleSort);
        List<SysRole> roleList = sysRoleService.list(queryWrapper);
        return Result.success(roleList);
    }
}